import store from '@/store/'

export const WebSocketMixin = {
    mounted() {
        //初始化WebSocket
        this.initWebSocket()
    },
    destroyed: function () { // 离开页面生命周期函数
        this.websock.close()
        // this.webSocketClose();
    },
    methods: {
        initWebSocket: function () {
            // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
            const userId = store.getters.getId;
            const url = window._CONFIG['project-name'].replace("https://", "ws://").replace("http://", "ws://") + "/socket/" + userId;
            this.websock = new WebSocket(url);
            this.websock.onopen = this.webSocketOnOpen;
            this.websock.onerror = this.webSocketOnError;
            this.websock.onmessage = this.webSocketOnMessage;
            this.websock.onclose = this.webSocketClose;
        },
        webSocketOnOpen: function () {
            console.log("WebSocket连接成功");
        },
        webSocketOnError: function (e) {
            console.log("WebSocket连接发生错误");
            // 异常重连
            this.reConnect();
        },
        webSocketOnMessage: function (e) {
            // **这个方法需要在被加入的组件中重新
            this.message = e;
            console.log("所有信息", this.message);
            console.log("接收内容", this.message.data);

            /*const data = eval("(" + e.data + ")");
            //处理订阅信息
            if (data.cmd == "topic") {
                //TODO 系统通知
                console.log(data);
            } else if (data.cmd == "user") {
                //TODO 用户消息
                console.log(data);
            }*/
        },
        webSocketClose: function (e) {
            console.log("connection closed (" + e.code + ")");
        },
        webSocketSend(text) {
            // **这个方法需要在被加入的组件中重新
            // 数据发送
            try {
                this.websock.send(text);
            } catch (err) {
                console.log("send failed (" + err.code + ")");
            }
        },
        reConnect() {
            let that = this;
            if (that.lockReconnect) return;
            that.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(function () {
                console.info("尝试重连...");
                that.initWebSocket();
                that.lockReconnect = false;
            }, 5000);
        },
    }
};
